package com.ruoyi.manage.enterprise.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.celoan.service.ExTradeEffectEnterprisesDetailService;
import com.ruoyi.common.core.domain.model.RegisterBody;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.ListUtil;
import com.ruoyi.common.utils.ObjUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StrUtil;
import com.ruoyi.common.utils.uuid.NumsUtils;
import com.ruoyi.manage.enterprise.domain.*;
import com.ruoyi.manage.enterprise.domain.vo.EcEnterpriseInformationVo;
import com.ruoyi.manage.enterprise.mapper.EcEnterpriseInformationMapper;
import com.ruoyi.manage.enterprise.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;


/**
 * 企业管理Service业务层处理
 *
 * @author ruoyi
 * @date 2025-07-27
 */
@Service
public class EcEnterpriseInformationServiceImpl extends ServiceImpl<EcEnterpriseInformationMapper, EcEnterpriseInformation> implements IEcEnterpriseInformationService {

    @Autowired
    IEcEnterpriseLegalService iEcEnterpriseLegalService;

    @Autowired
    ISysUserExpandService iSysUserExpandService;

    @Autowired
    IEcEnterpriseOperatorService iEcEnterpriseOperatorService;

    @Autowired
    IEcEnterpriseCheckService iEcEnterpriseCheckService;

    @Autowired
    IEcEnterpriseFileService iEcEnterpriseFileService;

    @Autowired
    IEcEnterpriseContactService iEcEnterpriseContactService;

    @Autowired
    ExTradeEffectEnterprisesDetailService exTradeEffectEnterprisesDetailService;

    @Override
    public EcEnterpriseInformation queryGetById(Long id) {
        EcEnterpriseInformation ecEnterpriseInformation = this.getById(id);
        return ecEnterpriseInformation;
    }

    @Override
    public EcEnterpriseInformationVo queryMoreGetById(Long id) {
        EcEnterpriseInformation ecEnterpriseInformation = this.getById(id);
        EcEnterpriseInformationVo informationVo = new EcEnterpriseInformationVo();
        BeanUtil.copyProperties(ecEnterpriseInformation, informationVo);
//        获取企业法人
        informationVo.setLegal(iEcEnterpriseLegalService.getOne(new QueryWrapper<EcEnterpriseLegal>().eq("enterprise_id", id)));

//        获取经办人
        if (StrUtil.isNotBlank(ecEnterpriseInformation.getAgentAuthFlag())) {
            informationVo.setOperator(iEcEnterpriseOperatorService.getOne(new QueryWrapper<EcEnterpriseOperator>().eq("enterprise_id", id)));
        }

//        设置企业联系人
        List<EcEnterpriseContact> contactList = iEcEnterpriseContactService.lambdaQuery().eq(EcEnterpriseContact::getEnterpriseId, id).list();
        informationVo.setContactList(contactList);

        return informationVo;
    }

    /**
     * 新增企业管理
     *
     * @param ecEnterpriseInformation 企业管理
     * @return 结果
     */
    @Override
    public boolean addEcEnterpriseInformation(EcEnterpriseInformation ecEnterpriseInformation) {
        boolean save = this.save(ecEnterpriseInformation);
        return save;
    }


    public void addEcenterpriseCheck(EcEnterpriseCheck enterpriseCheck) {
        iEcEnterpriseCheckService.save(enterpriseCheck);
    }


    public boolean addEcEnterpriseInformationAsync(RegisterBody registerBody) {
//        增加企业预检列表
        EcEnterpriseCheck ecEnterpriseCheck = EcEnterpriseCheck.builder()
                .companyName(registerBody.getCompanyName()).build();
        addEcenterpriseCheck(ecEnterpriseCheck);


//        增加企业信息
        EcEnterpriseInformation enterpriseInformation = new EcEnterpriseInformation();
        enterpriseInformation.setEnterpriseName(registerBody.getCompanyName());
//        增加关联表信息
        boolean save = this.save(enterpriseInformation);
        SysUserExpand userExpand = SysUserExpand.builder()
                .relatedId(ecEnterpriseCheck.getId())
                .relatedRemark(enterpriseInformation.getEnterpriseName())
                .userType(0)
                .mainSign(1)
                .userId(registerBody.getUserId())
                .provinceCode("130000")
                .cityCode("130400")
                .countyCode(registerBody.getLocalCode())
                .build();
        boolean sysExpandSave = iSysUserExpandService.save(userExpand);


        return save && sysExpandSave;
    }


    @Override
    @Transactional
    public boolean updateEnterpriseCertification(EcEnterpriseInformationVo ecEnterpriseInformationVo) {
        //        添加企业信息
        ecEnterpriseInformationVo.setAuthenticationFlag("1");
        ecEnterpriseInformationVo.setRealNameFlag("0");
        ecEnterpriseInformationVo.setAuthenticationTime(new Date());
        ecEnterpriseInformationVo.setExamineResult("0");
        boolean enterpriseSave = this.updateById(ecEnterpriseInformationVo);
        if (!enterpriseSave) {
            throw new CustomException("保存失败，请重试");
        }
//        插入企业法人信息
        EcEnterpriseLegal ecEnterpriseLegal = ecEnterpriseInformationVo.getLegal();
        EcEnterpriseLegal currentlagal = iEcEnterpriseLegalService.getOne(new QueryWrapper<EcEnterpriseLegal>().eq("enterprise_id", ecEnterpriseInformationVo.getId()), false);
        ecEnterpriseLegal.setId(currentlagal.getId());
        boolean legalSave = iEcEnterpriseLegalService.updateById(ecEnterpriseLegal);
        if (!legalSave) {
            throw new CustomException("保存失败，请重试");
        }


//       插入经办人信息
        if (StrUtil.isNotBlank(ecEnterpriseInformationVo.getAgentAuthFlag())) {
            EcEnterpriseOperator currenterpriseOperator = iEcEnterpriseOperatorService.getOne(new QueryWrapper<EcEnterpriseOperator>().eq("enterprise_id", ecEnterpriseInformationVo.getId()));
            EcEnterpriseOperator enterpriseOperator = ecEnterpriseInformationVo.getOperator();
            if (ObjUtil.isNotNull(currenterpriseOperator)) {
                enterpriseOperator.setId(currenterpriseOperator.getId());
                boolean operatorUdp = iEcEnterpriseOperatorService.updateById(enterpriseOperator);
                if (!operatorUdp) {
                    throw new CustomException("保存失败，请重试");
                }
            } else {
                enterpriseOperator.setEnterpriseId(ecEnterpriseInformationVo.getId());
                boolean operatorSave = iEcEnterpriseOperatorService.addEcEnterpriseOperator(enterpriseOperator);
                if (!operatorSave) {
                    throw new CustomException("保存失败，请重试");
                }
            }
        }

//       插入文件地址
        List<EcEnterpriseFile> fileList = ecEnterpriseInformationVo.getFileList();

        if (fileList != null && fileList.size() > 0) {
            iEcEnterpriseFileService.remove(new QueryWrapper<EcEnterpriseFile>().eq("enterprise_id", ecEnterpriseInformationVo.getId()));
            fileList.forEach(e -> {
                e.setEnterpriseId(ecEnterpriseInformationVo.getId());
                e.setFileNo(NumsUtils.generateCode("F"));
            });

            boolean fileSave = iEcEnterpriseFileService.saveBatch(fileList);
            if (!fileSave) {
                throw new CustomException("保存失败，请重试");
            }
        }

        return true;
    }


    /**
     * 添加企业信息
     */
    @Override
    @Transactional
    public boolean addEcEnterpriseCertification(EcEnterpriseInformationVo ecEnterpriseInformationVo) {
//        核验企业信息
        boolean exists = this.lambdaQuery().eq(EcEnterpriseInformation::getCreditCode, ecEnterpriseInformationVo.getCreditCode()).or().eq(EcEnterpriseInformation::getEnterpriseName, ecEnterpriseInformationVo.getEnterpriseName()).exists();
        if (exists) {
            throw new CustomException("企业信息已存在，请核验后提交");
        }
//        添加企业核验信息
        EcEnterpriseCheck ecEnterpriseCheck = EcEnterpriseCheck.builder()
                .companyName(ecEnterpriseInformationVo.getEnterpriseName())
                .creditCode(ecEnterpriseInformationVo.getCreditCode())
                .provinceName(ecEnterpriseInformationVo.getProvinceName())
                .provinceCode(ecEnterpriseInformationVo.getProvinceSiteId())
                .cityCode(ecEnterpriseInformationVo.getCitySiteId())
                .cityName(ecEnterpriseInformationVo.getCityName())
                .areaAdress(ecEnterpriseInformationVo.getAreaName())
                .areaCode(ecEnterpriseInformationVo.getAreaSiteId()).build();
        iEcEnterpriseCheckService.save(ecEnterpriseCheck);
        //      创建企业与用户关联关系
        if (ObjUtil.isNotNull(ecEnterpriseCheck.getId())) {
            boolean conenctSuccess = iSysUserExpandService.connectSysUserEnterprise(ecEnterpriseCheck);
            if (!conenctSuccess) {
                throw new CustomException("保存失败，请重试");
            }
        }

//        添加企业信息
        ecEnterpriseInformationVo.setAuthenticationTime(new Date());
        ecEnterpriseInformationVo.setAuthenticationFlag("1");
        boolean enterpriseSave = this.save(ecEnterpriseInformationVo);
        if (!enterpriseSave) {
            throw new CustomException("保存失败，请重试");
        }
//        插入企业法人信息
        EcEnterpriseLegal ecEnterpriseLegal = ecEnterpriseInformationVo.getLegal();
        ecEnterpriseLegal.setEnterpriseId(ecEnterpriseInformationVo.getId());
        boolean legalSave = iEcEnterpriseLegalService.save(ecEnterpriseLegal);
        if (!legalSave) {
            throw new CustomException("保存失败，请重试");
        }


//       插入经办人信息
        if (StrUtil.isNotBlank(ecEnterpriseInformationVo.getAgentAuthFlag())) {
            EcEnterpriseOperator enterpriseOperator = ecEnterpriseInformationVo.getOperator();
            enterpriseOperator.setEnterpriseId(ecEnterpriseInformationVo.getId());
            boolean operatorSave = iEcEnterpriseOperatorService.addEcEnterpriseOperator(enterpriseOperator);
            if (!operatorSave) {
                throw new CustomException("保存失败，请重试");
            }
        }

//       插入文件地址
        List<EcEnterpriseFile> fileList = ecEnterpriseInformationVo.getFileList();

        if (fileList != null && fileList.size() > 0) {
            fileList.forEach(e -> {
                e.setEnterpriseId(ecEnterpriseInformationVo.getId());
                e.setFileNo(NumsUtils.generateCode("F"));
            });

            boolean fileSave = iEcEnterpriseFileService.saveBatch(fileList);
            if (!fileSave) {
                throw new CustomException("保存失败，请重试");
            }
        }


        return true;
    }

    /**
     * 修改企业管理
     *
     * @param ecEnterpriseInformation 企业管理
     * @return 结果
     */
    @Override
    public boolean updateEcEnterpriseInformation(EcEnterpriseInformation ecEnterpriseInformation) {
        return this.updateById(ecEnterpriseInformation);
    }


    /**
     * 审核企业信息
     *
     * @param ecEnterpriseInformation 企业管理
     * @return 结果
     */
    @Override
    @Transactional
    public boolean checkEcEnterpriseInformation(EcEnterpriseInformation ecEnterpriseInformation) {
        //审核通过的同步企业上报表
        if ("2".equals(ecEnterpriseInformation.getExamineResult())) {
            try {
                exTradeEffectEnterprisesDetailService.generateShouquanshu(ecEnterpriseInformation.getId());
            } catch (Exception e) {
                e.printStackTrace();
            }
//            生成企业授权信息上报数据
        }
        return this.updateById(ecEnterpriseInformation);
    }

    /**
     * 批量删除企业管理
     *
     * @param ids 需要删除的企业管理主键
     * @return 结果
     */
    @Override
    public boolean deleteEcEnterpriseInformationByIds(String[] ids) {
        return this.removeByIds(ListUtil.toList(ids));
    }

    @Override
    public List<EcEnterpriseInformation> selectEnterpriseByUserId(EcEnterpriseParams params) {

        params.setUserId(SecurityUtils.getUserId());
        List<EcEnterpriseInformation> list = baseMapper.selectEnterpriseByUserId(params);
        return list;
    }

    @Override
    public EcEnterpriseInformation selectMainEnterpriseByUserId() {
        Long userId = SecurityUtils.getUserId();
        return baseMapper.selectMainEnterpriseByUserId(userId);
    }

}
